﻿using System.Collections.Generic;
using IDAL;
using Model;
using NHibernate;

namespace SqlDALLibrary
{
    public class FavouriteDal : IFavouriteDAL
    {
        public void saveFavorite(Favourite favourite)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Save(favourite);
                tx.Commit();
            }
            session.Close();
        }

        public void delFavorite(Favourite favourite)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Delete(favourite);
                tx.Commit();
            }
            session.Close();
        }

        public IList<Favourite> getFavourite(User user)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<Favourite> favoriteList = session
                    .CreateQuery("from Favourite f where f.user=:user")
                    .SetParameter("user", user)
                    .List<Favourite>();
            session.Close();
            return favoriteList;
        }

        public IList<Favourite> getFavourite(Resource resource)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<Favourite> favoriteList = session
                    .CreateQuery("from Favourite f where f.resource=:resource")
                    .SetParameter("resource", resource)
                    .List<Favourite>();
            session.Close();
            return favoriteList;
        }

        public Favourite getFavourite(User user, Resource resource)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            Favourite favourite = session
                    .CreateQuery("from Favourite f where f.user=:user and f.resource=:resource")
                    .SetParameter("user", user).SetParameter("resource",resource)
                    .UniqueResult<Favourite>();
            session.Close();
            return favourite;
        }

        public Favourite getFavourite(int favouriteId)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            Favourite favourite = session
                    .CreateQuery("from Favourite f where f.id=:id")
                    .SetInt32("id", favouriteId)
                    .UniqueResult<Favourite>();
            session.Close();
            return favourite;
        }



    }
}
